<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>裁剪上传原理</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      padding-top: 40px;
      min-height: inherit;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;
    }

    button {
      width: 180px;
      height: 60px;
      outline: none;
      border: none;
      cursor: pointer;
      border-radius: 4px;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <input type="file">
  <img class="preview">
  <button>生成截图后的File对象</button>
</body>
<script>
  "use strict"; {
    const iptFile = document.querySelector(`input[type="file"]`);
    const img = document.querySelector(".preview");
    const btn = document.querySelector("button");

    iptFile.addEventListener("change", e => {
      let file = e.target.files[0];

      let reader = new FileReader();
      reader.addEventListener("load", e => {
        // 实现本地预览
        img.src = e.target.result;
      });

      // 读取文件
      reader.readAsDataURL(file);
    });


    let cutInfo = {
      // 裁剪的x坐标
      x: 500,
      // 裁剪的y坐标
      y: 200,
      // 裁剪的宽度尺寸
      cutWidth: 200,
      // 裁剪的高度尺寸
      cutHeight: 200,
      // 裁剪结果缩放后的尺寸--
      width: 100,
      height: 100,
    };

    btn.addEventListener("click", () => {
      const canavs = document.createElement("canvas");
      canavs.width = cutInfo.width;
      canavs.height = cutInfo.height;

      const ctx = canavs.getContext("2d");

      // 后面两个是参数是缩放的
      ctx.drawImage(img, cutInfo.x, cutInfo.y, cutInfo.cutWidth, cutInfo.cutHeight, 0, 0, cutInfo.width, cutInfo.height);

      canavs.toBlob(blob => {
        // blod 数据转为 file 文件
        let file = new File([blob], "avatar.png", {
          type: "image/png",
        });
        console.log("file", file);
      }, "image/png");

      document.body.appendChild(canavs);
    });
  };
</script>

</html>